import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Query,
  Req,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import Constants from '../common/constants';
import {
  ApiBearerAuth,
  ApiBody,
  ApiOperation,
  ApiParam,
  ApiQuery,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import { AssignRolesDto } from './dto/assign-roles.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { User } from './entities/user.entity';
import { HasRoles } from '../role/role.decorator';
import { Public } from '../common/isPublic';
import { RedisService } from '../redis/redis.service';
import RoleEnum from '../role/entities/RoleEnum';
import { Like } from 'typeorm';
import { HasPermission } from '../permission/permission.decorator';

/**
 * 只有roles=[SuperAdmin],用户角色为Admin.不可以访问
 */
@ApiTags('用户相关')
@Controller('users')
@HasRoles([RoleEnum.Admin, RoleEnum.SuperAdmin])
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    private readonly redisService: RedisService,
  ) {}

  @Post()
  @ApiOperation({ summary: '注册' })
  @ApiResponse({
    status: 201,
    description: '用户创建成功',
    type: CreateUserDto,
  })
  // @HasPermission('user:create')
  create(@Body() createUserDto: CreateUserDto) {
    console.log('users.controller.ts-create-createUserDto', createUserDto);
    return this.usersService.create(createUserDto);
  }

  @Post(':id/roles')
  @ApiOperation({ summary: '分配角色给用户' })
  @ApiParam({ name: 'id', description: '用户ID', example: 1 })
  @ApiBody({ type: AssignRolesDto }) // 指定请求体类型
  @ApiResponse({ status: 200, description: '角色分配成功' })
  @HasRoles([RoleEnum.SuperAdmin])
  async assignRolesToUser(
    @Param('id') id: string,
    @Body() assignRolesDto: AssignRolesDto, // 使用DTO类型注解请求体参数
  ) {
    return this.usersService.assignRolesToUser(id, assignRolesDto.roleId);
  }

  /**
   * 超级管理员可以查询is_deleted为true和false
   * 普通管理员可以查询is_deleted为false的
   * 普通用户不可以查询
   * @param query
   * @param request
   */
  @Get()
  @ApiOperation({ summary: '查询全部用户' })
  @ApiQuery({ name: 'currentPage', type: Number, required: false })
  @ApiQuery({ name: 'pageSize', type: Number, required: false })
  @ApiQuery({ name: 'username', type: String, required: false })
  @ApiQuery({ name: 'email', type: String, required: false })
  @ApiQuery({ name: 'phone', type: String, required: false })
  @ApiResponse({
    status: 200,
    description: '用户列表返回成功',
    type: [User],
  })
  // @HasPermission('user:select')
  @HasRoles([RoleEnum.Admin])
  async findAll(@Query() query: QueryUserDto, @Req() request: Request) {
    // 首先从缓存中查询用户的角色信息
    const userInfo = await this.redisService.get(
      request.headers[`${Constants.Access_Token}`],
    );
    if (!userInfo) {
      return {
        code: 401,
        message: '请先登录',
      };
    }
    const user = JSON.parse(userInfo);

    const whereCondition = this.generationQueryCondition(
      query,
      user.role.roleName as RoleEnum,
    );
    console.log('users.controller.ts-findAll-user', user);
    return this.usersService.findAll(
      { currentPage: 1, pageSize: 10, ...query },
      whereCondition,
    );
  }

  @Get(':id')
  @ApiOperation({ summary: '根据ID查询单个用户' })
  @ApiParam({ name: 'id', description: '用户ID', example: 1 })
  @ApiResponse({
    status: 200,
    description: '用户信息返回成功',
    type: CreateUserDto,
  })
  @ApiResponse({ status: 404, description: '用户不存在' })
  // @HasPermission('user:select')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新用户信息' })
  @ApiParam({ name: 'id', description: '用户ID', example: 1 })
  @ApiResponse({
    status: 200,
    description: '用户更新成功',
    type: UpdateUserDto,
  })
  @HasRoles([RoleEnum.SuperAdmin])
  @HasPermission('user:update')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.usersService.update(id, updateUserDto);
  }

  @Delete()
  @ApiOperation({ summary: '批量删除用户' })
  @ApiResponse({
    status: 200,
    description: '批量删除用户成功',
  })
  @HasRoles([RoleEnum.SuperAdmin])
  @HasPermission('user:delete')
  batchDelete(@Body('ids') ids: string[]) {
    return this.usersService.batchDelete(ids);
  }

  @Post('info')
  @ApiOperation({ summary: '获取登录用户信息' })
  @ApiBearerAuth() // 表示这个端点需要认证
  @ApiResponse({ status: 200, description: '用户信息返回成功' })
  @ApiResponse({ status: 401, description: '未授权的访问' })
  // @HasPermission('user:select')
  userInfo(@Req() req: Request) {
    const token = req.headers[`${Constants.Access_Token}`];
    return this.usersService.userInfo(token);
  }

  /**
   * 根据用户角色来生成不同的查询条件
   * SuperAdmin:可以查询is_deleted为true和false
   * Admin:可以查询is_deleted为false的
   * @param query 前端传递的查询条件,
   * @param role 角色
   */
  generationQueryCondition(query: QueryUserDto, role: RoleEnum) {
    const queryCondition = {
      ...(query.username && { username: Like(`%${query.username}%`) }),
      ...(query.phone && { phone: Like(`%${query.phone}%`) }),
      ...(query.email && { email: Like(`%${query.email}%`) }),
    };
    const whereConditionMap = {
      [RoleEnum.SuperAdmin]: {
        ...queryCondition,
      },
      [RoleEnum.Admin]: {
        ...queryCondition,
        is_deleted: false,
      },
    };

    return whereConditionMap[role];
  }
}
